﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing;

/*
 * TH07 Groep 10
 * ----------------------------------------------------------------------------------
 * Versie   Door        Commentaar
 * 0.1      Mike        Opzet en programmeer werk
 * 0.2      Erwin       Verplaatst naar Algorithms, 
 *                      aangepast om als reference te gebruiken
 */

namespace Algorithms.Noise
{
    public class SaltAndPepper
    {
        public static Bitmap CreateNoise(double intensity, Bitmap source)
        {
            int imageWidth = source.Width;
            int imageHeight = source.Height;
            Bitmap output = new Bitmap(imageWidth, imageHeight);
            BitmapData outputData = output.LockBits(new Rectangle(
                0, 0, imageWidth, imageHeight), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
            BitmapData sourceData = source.LockBits(new Rectangle(
                0, 0, imageWidth, imageHeight), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            int totalWidth = imageWidth * 3;
            int srcOffset = sourceData.Stride - totalWidth;
            int optOffset = outputData.Stride - totalWidth;

            double pr = 1.0 - intensity / 100.0;
            int count = 0;

            unsafe
            {
                byte* srcPnt = (byte*)sourceData.Scan0;
                byte* optPnt = (byte*)outputData.Scan0;
                Random r = new Random();
                double random = 0.0;
                for (int y = 0; y < imageHeight; y++)
                {
                    for (int x = 0; x < imageWidth; x++)
                    {
                        random = 2.0 * (r.Next(32767) - 32767 / 2.0) / 32767;
                        if (random > pr)
                        {
                            optPnt[0] = 255;
                            optPnt[1] = 255;
                            optPnt[2] = 255;
                            ++count;
                        }
                        else if (random < -pr)
                        {
                            optPnt[0] = 0;
                            optPnt[1] = 0;
                            optPnt[2] = 0;
                            ++count;
                        }
                        else
                        {
                            optPnt[0] = srcPnt[0];
                            optPnt[1] = srcPnt[1];
                            optPnt[2] = srcPnt[2];
                        }
                        srcPnt += 3;
                        optPnt += 3;
                    }
                    srcPnt += srcOffset;
                    optPnt += optOffset;
                }
            }
            output.UnlockBits(outputData);
            source.UnlockBits(sourceData);
            return output;
        }
    }
}
